package lua.compiler.tokens;
import java.util.logging.Logger;

import lua.compiler.CompilerException;
import lua.compiler.CtsType;
import lua.compiler.Function;
import lua.compiler.Functions;

import org.antlr.runtime.tree.Tree;


public class AssignToken extends GenericToken {
	static Logger logger = Logger.getAnonymousLogger();
	
	@Override
	public void parseImpl(Tree tree, Function function) throws CompilerException {
		Tree rvalue = tree.getChild(1);
		Tree lvalue = tree.getChild(0);
		
		String ltoken = Tokens.getToken(lvalue.getType());
		String rtoken = Tokens.getToken(rvalue.getType());

		if (!"NAME".equals(ltoken)) {
			throw new CompilerException(
				tree, lvalue + " nie jest l-wartoscia, nie mozna przypisac");
		}
		
	
		if ("CALL".equals(rtoken)) {
			String calledName = rvalue.getChild(0).getText();
			Function calledFunction = Functions.getFunction(calledName);
			if (calledFunction == null) {
				throw new CompilerException(
					tree, "Funkcja '" + calledName + "' nie jest zdefiniowana");
			}
			if  ("void".equals(calledFunction.getReturnType())) {
				throw new CompilerException(
					tree, "Nie mozna przypisywac wartosci void");
			}
		}
		else if ("STRING".equals(rtoken)) {
			function.addInstruction("ldstr " + rvalue.getText());
		}
		
		
		// generuje kod umieszczajacy przypisanie na stosie
		StmtToken stmtToken = new StmtToken();
		stmtToken.parse(rvalue, function);
		CtsType stmtType = stmtToken.getCtsType(); 
		
	
		String name = lvalue.getText();
		CtsType localType = function.getLocal(name);
				
		if (localType != null) {
			function.setLocal(tree, name, stmtType);
		}
		else if (function.getParam(name) != null) {
			function.setParam(tree, name, stmtType);
		}
		else 
			function.setLocal(tree, name, stmtType);
		
		
		String varName = lvalue.getText();
		function.addInstruction("stloc " + varName); // zapisujemy do lewej strony wyrazenia
	}
}
